package com.kfm.login.interceptor;

import com.kfm.login.util.Constant;
import com.kfm.login.util.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("TokenInterceptor" + request.getRequestURI());
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                if (Constant.TOKEN_KEY.equals(cookie.getName())){
                    return true;
                }
            }
        }

        // 没有 token，生成 token
        setToken(response);
        return true;
    }

    private String setToken(HttpServletResponse response){
        String token = StringUtil.uuid();
        // 存 cookie
        Cookie cookie = new Cookie(Constant.TOKEN_KEY, token);
        response.addCookie(cookie);
        return token;
    }
}
